import { useState, useEffect } from 'react'
import { WhiteSpace } from 'antd-mobile'
import router from 'umi/router'
import QRCode from 'qrcode.react'
import { Icon, Empty } from 'antd'
import services from '@/services'
import styles from './index.scss'

const { SBMy } = services
const Index = () => {
  const [cards, setCards] = useState([])
  const openId = localStorage.getItem('openId')

  useEffect(() => {
    if (openId) {
      SBMy({
        sign: `${openId}$$##1234ech**`.MD5(32),
        data: openId
      })
        .then(res => {
          console.log('我的预约列表', res)
          if (res.success) {
            setCards(res.data.orders)
          }
        })
    }
  }, [openId])
  return (
    <div className={styles.wait}>
      <WhiteSpace />
      <div className={styles.title}>我的预约</div>
      {
        cards.length
          ? cards.map(i => <Card_ card={i} className={styles.card} key={i.code} />)
          : <Empty description='暂无预约' />
      }
    </div>
  )
}

const Card_ = ({ card }) => {
  const { item, branch, regdate, state, qrCode } = card
  const today = isToday(regdate)

  const onActiveClick = (query, today) => {
    router.push(`/detail?code=${query.code}&today=${today}`)
  }

  return (
    <div className={styles.flex}>
      <div className={styles.code}>
        <QRCode
          value={qrCode}  // value参数为生成二维码的链接
          size={60} // 二维码的宽高尺寸
          fgColor="#000000"  // 二维码的颜色
        />
      </div>
      <div className={styles.content}>
        <div className={styles.item}>
          <div><Icon type="unordered-list" className={styles.icon} />{item} - {branch}</div>
          <div>预约时间：<span>{regdate}</span></div>
          <div>预约网点：{branch}</div>
          <div>预约状态：<span>{state === 0 ? '未激活' : (state === 1 ? '已激活' : '过期')}</span></div>
        </div>
        <div className={styles.active} onClick={() => onActiveClick(card, today)}>
          {
            today
              ? <a>查看&激活</a>
              : <a>取消激活</a>
          }
        </div>
      </div>
    </div>
  )
}

function isToday(date) {
  //Code goes here.
  var d = new Date(date.toString().replace(/-/g, "/"));
  var todaysDate = new Date();
  if (d.setHours(0, 0, 0, 0) == todaysDate.setHours(0, 0, 0, 0)) {
    return true;
  } else {
    return false;
  }
}

export default Index
